const router = require('koa-router')()
const uploader = require('../uploader')
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const util = require('util')
const stats = require('../helpers/stats')
const rename = util.promisify(fs.rename)
const comments = require('../helpers/comments')
const unlink = util.promisify(fs.unlink)


router.prefix('/images')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
// 上传图片，临时文件
router.post('/', uploader.single('file'), async function (ctx, next) {
    let file = ctx.req.file
    let diskFilename = file.filename + path.extname(file.originalname)
    await rename(file.path, path.dirname(file.path) + '/' + diskFilename)
        .then(() => Image.create({
            title: ctx.req.body.title,
            description: ctx.req.body.description,
            filename: diskFilename,
            mimetype: ctx.req.file.mimetype,
            originalname: ctx.req.file.originalname
        }))
        .then(doc => ctx.redirect(`/images/${doc.id}`))
        .catch(err => ctx.throw(500, err))
})
// 评论实现
router.post('/:imageid/comment', async function (ctx, next) {

  await Image.findById(ctx.params.imageid)
  .then((image) => Comment.create({
    image_id:image._id,
    email:ctx.request.body.email,
    name:ctx.request.body.name,
    gravatar:ctx.request.body.email,
    comment:ctx.request.body.comment
  }))
  .then(doc => ctx.response.redirect('/images/' + doc.image_id + '#' + doc._id))
  .catch(err => ctx.throw(500, err))
})
// 浏览数量统计
router.get('/:imageid',async function(ctx, next) {
    let image = await Image.findById(ctx.params.imageid)
    image.views = image.views + 1
    await image.save()
    await Promise.all([
        stats(),
        Image.find().sort({likes:-1}).limit(9),
        comments(),
        Comment.find({ image_id:ctx.params.imageid})
    ])
    .then(([stats, popular, comments, pImages]) => ctx.render('image',{image,popular, stats, comments,pImages}))
    .catch(err => ctx.throw(500,err))
})
// 删除图片
router.delete('/:imageid', async function (ctx, next) {
  let image = await Image.findById(ctx.params.imageid)
  await unlink(path.resolve('./public/upload/' + image.filename))
  .then(() => Image.deleteOne({_id : ctx.params.imageid}))
  .then(() => Comment.deleteMany({image_id : ctx.params.imageid}))
  .then(() => ctx.body = { res: true })
  .catch(err => ctx.throw(500, err))
})
// 删除评论
router.delete('/:imageid/:commentid', async function (ctx, next) {
   Comment.deleteOne({_id : ctx.params.commentid})
  .then(() => ctx.response.redirect('/images/' + ctx.params.imageid))
  .catch(err => ctx.throw(500, err))
})
// 点赞统计
router.post('/like', async ctx => {
    await Image.findByIdAndUpdate(ctx.request.body.imageid, {$inc: {likes: 1}})
    .then(() => Image.findById(ctx.request.body.imageid).select('likes'))
    .then(doc => ctx.body = doc)
    .catch(err => ctx.throw(500, err))
})
// 评论统计
module.exports = router
